package com.sunwayworld.dev.io.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class GenerateUtils {
	private Configuration cfg = null;

	public GenerateUtils() {
		if (null == cfg) {
			cfg = new Configuration();
		
			cfg.setClassForTemplateLoading(this.getClass(),
			"/");
			cfg.setDefaultEncoding("utf-8");
		}
	}

	public boolean generate(String template, String descpath, Map map) {
		try {
			Template t = cfg.getTemplate(template);

			File descfile = new File(descpath);
			File parentsfile = descfile.getParentFile();

			if (!parentsfile.exists()) {
				parentsfile.mkdirs();
			}

			if (!descfile.exists()) {
				descfile.createNewFile();
			} else {
				descfile.createNewFile();
			}

			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(descfile),"utf-8"));

			t.process(map, out);

		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
}
